package com.csmarket.csmarketbackend.config;

import com.csmarket.csmarketbackend.utils.JwtUtils;
import jakarta.websocket.HandshakeResponse;
import jakarta.websocket.server.HandshakeRequest;
import jakarta.websocket.server.ServerEndpointConfig;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.List;
import java.util.Map;
@Component
public class WebSocketConfigurator extends ServerEndpointConfig.Configurator {


    @Override
    public void modifyHandshake(ServerEndpointConfig config, HandshakeRequest request, HandshakeResponse response) {
        Map<String, List<String>> headers = request.getHeaders();//获取请求头
        System.out.println("Received headers: " + headers); // 添加这行来查看所有请求头
        List<String> authHeaders = headers.get("Authorization");//获取Authorization头

        if (authHeaders != null && !authHeaders.isEmpty()) {
            String authHeader = authHeaders.get(0);
            if (authHeader != null && authHeader.startsWith("Bearer ")) {
                String token = authHeader.substring(7);
                try {
                    JwtUtils jwtUtils=new JwtUtils();
                    String username = jwtUtils.parseToken(token);
                    System.out.println("WebSocket认证成功，用户名: " + username); // 增强日志
                    config.getUserProperties().put("username", username);
                } catch (Exception e) {
                    System.out.println("WebSocket认证失败: " + e.getMessage());
                }


            }
        }
    }
}
